package jxau.jwgl.service.impl;

import jxau.jwgl.api.CommonDataApi;
import jxau.jwgl.api.JWGLServerException;
import jxau.jwgl.api.MessageData;
import jxau.jwgl.api.WebApiFactory;
import jxau.jwgl.commons.entity.CourseCategory;
import jxau.jwgl.commons.entity.Semester;
import jxau.jwgl.service.CommonDataService;
import jxau.jwgl.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;

/**
 * CommonDataServiceImpl
 *
 * @author LongShu 2017/06/09
 */
@Service
public class CommonDataServiceImpl implements CommonDataService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private CommonDataApi commonDataApi = WebApiFactory.get(CommonDataApi.class);

    @Autowired
    private UserService userService;

    @Override
    @Cacheable(cacheNames = "commonData", key = "'semesterList'+#username")
    public List<Semester> semesterList(String username) {
        String guid = userService.getGuid(username);
        try {
            Response<MessageData<Semester>> response = commonDataApi.semesterList(guid).execute();
            MessageData<Semester> messageData = response.body();
            return messageData.getData();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            throw new JWGLServerException("教务系统错误,获取学期列表失败!");
        }
    }

    @Override
    @Cacheable(cacheNames = "commonData", key = "'courseCategory'+#username")
    public List<CourseCategory> courseCategory(String username) throws JWGLServerException {
        String guid = userService.getGuid(username);
        try {
            Response<List<CourseCategory>> response = commonDataApi.courseCategory(guid).execute();
            List<CourseCategory> courseCategoryList = response.body();
            return courseCategoryList;
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            throw new JWGLServerException("教务系统错误,获取课程分类失败!");
        }
    }

}
